<template>
  <div class="poemEnd" :style="poemStyle">
    <div class="main">
      <div class="opacityBg" v-if="picbookIndex.id===71" :style="bgBoxStyle"></div>
      <div class="poemMain" :style="picbookIndex.id===71 ? poemMainStyle : ''">
        <div class="poem-title" :style="titleStyle">{{poem.name}}</div>

        <!--          作者71（我盼妈妈早回家-->
        <div class="rhyme-author" v-if="picbookIndex.id===71">
          文/{{picbook.detail.wordAuthor}}
          画/{{picbook.detail.imageAuthor}}
        </div>

        <!--          普通-->
        <div class="poem-author" v-if="picbookIndex.id!==71">
          {{poem.reign}}
          {{poem.author}}
        </div>

        <!--          中间阅读部分-->
        <div class="poemContain" :style="picbookIndex.id===71? poemContainStyle :''">
          <div class="poem-content" v-for="(wordItems,lineIndex) in lineWord" :key="lineIndex"
               :style="poemContentStyle">
            <div class="activeWord" v-for="(word,index) in wordItems" :key="index"
                 :style="activeWordStyle(word,lineIndex)">
              {{word.text}}
              <audio type="audio/mpeg" :src="audioUrl(index,lineIndex)" :ref="'wordAudio' + index" v-if="endShow"></audio>
            </div>
          </div>
        </div>

      </div>

      <!--      尾页按钮-->
      <div class="end-content" :style="endStyle" v-show="endShow">
        <div class="audition" :style="auditionStyle" @touchend.stop = "audioStart?poemPlay():null"></div>
        <div class="again-listening" @touchend.stop = "againStart"></div>
      </div>

      <!--      首页按钮开始-->
      <div class="start" v-show="beginShow"
           @touchend="startTouch" :style="endStyle">
        <!--    首页音乐-->
        <audio type="audio/mpeg" :src="poem.contentAudioUrl" ref="contentAudio"></audio>
      </div>
    </div>
  </div>
</template>

<script>
  import { mapActions, mapGetters } from "vuex"
  // eslint-disable-next-line no-unused-vars
  const $ = window.$
  export default {
    props: ['poemContent','lineLength','beginShow','endShow'],
    data() {
      return {
        audioStart: true,
        timerList: [],
        lineWord: [],
      }
    },
    created() {
      //用符号分隔  普通绘本
      const splitLine = this.poemContent.map(item=>{
        return item.split(/[，。]/g).filter(item => {return item.length>0})
      })
      const line = splitLine.reduce(function (a, b) { return a.concat(b)} )
      // 加上标点符号
      this.lineWord = line.map((item,index) =>{
        const wordItem = [...item]
        if(index % 2 === 0){
          wordItem.push('，')
        } else {
          wordItem.push('。')
        }
        return wordItem
      })

      // 对象化
      this.lineWord = this.lineWord.map(item => {
        const options = [...item]
        for (const index in options) {
          options[index] = {
            text: options[index],
            isActive: false,
          }
        }
        return options
      })
    },
    beforeMount() {
      this.lineWord.forEach(word =>{
        word.forEach(item =>{
          this.$set(item, 'isActive', false)
        })
      })
    },
    mounted() {
      //播放首页音乐
      if(this.beginShow){
        setTimeout(() => {
          this.$refs.contentAudio.play()
        }, 500)
      }
    },
    beforeDestroy() {
      this.timerList.map(item => {
        clearTimeout(item)
      })
    },
    computed: {
      picbook() {
        return this.picbookList.filter(item => { return item.id === this.picbookIndex.id })[0]
      },
      //首页背景
      poemStyle() {
        return {
          background: "url(" + this.poem.pageBeginBackgroundImageUrl + ")0 0/100% 100%"
        }
      },
      auditionStyle() {
        return {
          background: "url(" + this.variable.STATICE_URLTITLE + 'poem/试听图标.png' + ")0 0/100% 100%",
          filter: this.audioStart ? 'none' : 'grayscale(1)'
        }
      },
      endStyle(){
        return{
          marginLeft: this.picbookIndex.id === 71 ? '-13rem' : '',
          top: this.picbookIndex.id === 71 ? '90%' : ''
        }
      },

      //我盼妈妈早回家
      poemMainStyle(){
        return{
          transform: 'translate3d(-9rem,-2.5rem,0)',
        }
      },
      poemContainStyle(){
        return{
          marginTop: '4rem'
        }
      },
      //标题样式
      titleStyle(){
        return{
          fontSize: this.picbookIndex.id === 71 ? '1.5rem' : '',
          letterSpacing: this.picbookIndex.id === 71 ?'0.2rem' : '',
          color: this.picbookIndex.id === 71 ? 'rgb(129,49,18)' : 'rgba(0,0,0,0.8)',
        }
      },
      //作者
      // authorStyle(){
      //   return{
      //     top: '2.5rem',
      //     color: 'rgb(129,49,18)',
      //     letterSpacing: '0rem',
      //   }
      // },
      //中间每一行的样式
      poemContentStyle(){
        return{
          height: this.picbookIndex.id === 71 ? '1.7rem' : '',
          lineHeight: this.picbookIndex.id === 71 ? '1.7rem' : ''
        }
      },
      //激活状态样式
      // eslint-disable-next-line no-unused-vars
      activeWordStyle(word,lineIndex) {
        return function (word,lineIndex) {
          return {
            width: word.text === '，' || word.text === '。' ? '1rem' : 15 / (this.lineLength[lineIndex] + 1) + 'rem',
            color: word.isActive ? 'rgb(252,136,90)' : this.picbookIndex.id === 71 ? 'rgb(129,49,18)' : 'rgba(0,0,0,0.8)',
            fontSize:word.isActive ? this.picbookIndex.id === 71 ? '1.6rem' : '2rem' :
                    this.picbookIndex.id === 71 ? '1.3rem' : '1.5rem',
            transition: 'all 0.5s'
          }
        }
      },
      //音频效果
      audioUrl(index,lineIndex) {
        return function (index,lineIndex) {
          if(this.lineWord[lineIndex][index].text === '，' || this.lineWord[lineIndex][index].text === '。'){
            return
          } else {
            // //符号后面的语音往前调  假数据
            // for(let i = 0; i < this.lineWord[lineIndex].length; i++){
            //   if(index > i && index < this.lineWord[lineIndex].length){
            //     if(this.lineWord[lineIndex][index-i].text === '，') index--
            //   }
            // }
            for(let i = 0; i < lineIndex; i++) {
              index+=(this.lineLength[i])
            }
            return this.poem.wordAudioUrlPrefix + this.poem.wordAudioFileNames[index]
          }
        }
      },
      //用户节奏数组
      record() {
        let arr = [],spliceArr = []
        for (let index in Object.keys(this.poemBeatSeconds)) {
          const item = this.poemBeatSeconds[index]
          for (let i = 0; i < item.length; i++) {
            if (index > 0) {
              const lastTime = this.poemBeatSeconds[index - 1][this.poemBeatSeconds[index - 1].length - 1]
              item[i] = item[i] + lastTime + 1000
            }
            arr.push(item[i])
          }
        }

        this.lineLength.forEach(item =>{
          let itemSplice = arr.splice(0,item)
          spliceArr.push(itemSplice)
        })
        return spliceArr
      },
      bgBoxStyle(){
        return{
          background: 'url(' + this.poem.pageBeginBoxImageUrl + ")0 0/100% 100%"
        }
      },
      ...mapGetters("poemStatus", {
        poemBeatSeconds: "gerPoemBeatSeconds",
        poem: "getPoem"
      }),
      ...mapGetters("picbookListStatus", {
        picbookIndex: "getPicbookIndex",
        picbookList: "getPicbookList"
      }),
    },
    methods: {
      //首页开始
      startTouch: function () {
        this.touchMusic()
        this.$emit("poemStart")
      },
      //点击播放
      poemPlay: function () {
        this.audioStart = false
        this.timerList.map(item => {
          clearTimeout(item)
        })
        for (let recordIndex = 0; recordIndex < this.record.length; recordIndex++) {
          for (let i = 0; i < this.record[recordIndex].length; i++){
            const timer = setTimeout(() => {
              const wordAudio = 'wordAudio' + i
              this.$refs[wordAudio][recordIndex].play()
              this.$set(this.lineWord[recordIndex][i], 'isActive', true)
              if (i > 0) this.$set(this.lineWord[recordIndex][i - 1], 'isActive', false)
              //把上一行的关闭
              if(i===0 && recordIndex>0) {
                this.lineWord[recordIndex-1].forEach(item=>{this.$set(item, 'isActive', false)})
              }
              //全部读完
              if(recordIndex === this.record.length - 1 && i === this.record[recordIndex].length - 1){
                setTimeout(()=>{
                  this.audioStart = true
                  this.$set(this.lineWord[recordIndex][i], 'isActive', false)
                },500)
              }
            }, this.record[recordIndex][i])
            this.timerList.push(timer)
          }
        }

        //接口
        const json = {
          deviceUuid: this.deviceUuid,
          picbookId: this.picbookIndex.id,
          value: { poemBeatSeconds: this.poemBeatSeconds }
        }
        console.log(json);
        this.$post(this.api.poemSaveRecord, json).then(
                // eslint-disable-next-line no-unused-vars
                res => { },
                // eslint-disable-next-line no-unused-vars
                err => {
                  this.setPopup({
                    content: "播放失败,请检查网络"
                  })
                }
        )
      },

      //    重置按钮
      againStart: function () {
        this.timerList.map(item => {
          clearTimeout(item)
        })
        this.touchMusic()
        this.$emit("poemAgain")
        const json = {
          deviceUuid: this.deviceUuid,
          picbookId: this.picbookIndex.id,
          value: null
        }
        this.$post(this.api.poemSaveRecord, json).then(res => { console.log("重置成功") })
      },
      ...mapActions("mainStatus", ["setPopup"]),
    }
  };
</script>

<style scoped lang='stylus'>
  .poemEnd
    position absolute
    width 100%
    height 100%
    z-index 99
    .main
      position absolute
      width 100vw
      height 100vh
      transform translate(calc(0px - var(--X)), calc(0px - var(--Y)))
    .opacityBg
      position absolute
      $center('WHLT', 18rem, 20rem)
      margin-left -18rem
      margin-top -11.5rem
    .balladMain
      position absolute
      $center('WHLT', 14rem, 18rem)
      margin-left -16rem
      margin-top -10.5rem
    .activeBalladWord
      position absolute
      width 1.5rem
      height 1.5rem
    .poemMain
      position absolute
      $center('WHLT', 15rem, 15rem)
      height auto
      .poem-title
        $coord('WHLT',15rem,2.5rem,0,0rem)
        font-size 2.5rem
        font-weight bold
        letter-spacing 0.7rem
        color rgba(0,0,0,0.8)
        text-align center
        line-height 2.5rem
        text-shadow: -2px 0 #fff, 0 2px #fff, 2px 0 #fff, 0 -2px #fff
      .rhyme-author
        $coord('WHLT',15rem,1.2rem,0,2.5rem)
        font-size 1rem
        letter-spacing 0rem
        color rgb(129,49,18)
        text-align center
        line-height 1rem
        text-shadow: -2px 0 #fff, 0 2px #fff, 2px 0 #fff, 0 -2px #fff
      .poem-author
        $coord('WHLT',15rem,1.2rem,0,3rem)
        font-size 1rem
        letter-spacing 0.3rem
        color rgba(0,0,0,0.8)
        text-align center
        line-height 1.2rem
        text-shadow: -2px 0 #fff, 0 2px #fff, 2px 0 #fff, 0 -2px #fff
      .poemContain
        margin-top 5rem
        height auto
        .poem-content
          display flex
          align-content center
          justify-content center
          width 15rem
          height 2.2rem
          .activeWord
            height 2.2rem
            line-height 2.2rem
            text-align center
            text-shadow: -2px 0 #fff, 0 2px #fff, 2px 0 #fff, 0 -2px #fff
  .end-content
    position absolute
    $center('WHLT', 10rem, 3rem)
    top 85%
    .audition
      width 6rem
      height 100%
      position absolute
      left 0
      top 0
    .again-listening
      width 3rem
      height 3rem
      position absolute
      margin-left 1rem
      left 6rem
      top 0
      background url($urlTitle + 'poem/重录图标.png') 0 0 / 100% 100%
  .start
    position absolute
    $center('WHLT', 6rem, 2.8rem)
    top 85%
    background url($urlTitle + 'poem/开始.png') 0 0 / 100% 100%
</style>
